package com.zretc.emptraining.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.emptraining.dbtools.PageData;
import com.zretc.emptraining.entity.Course;
import com.zretc.emptraining.service.CourseService;
import com.zretc.emptraining.serviceimpl.CourseServiceImpl;
import com.zretc.emptraining.dbtools.AjaxResponse;

/**
 * 课程 控制层
 * 
 * @author 傅洁敏
 */

/*
 * Servlet implementation class CourseServlet
 */
@WebServlet("/CourseServlet")
public class CourseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	CourseService cs = new CourseServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CourseServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置编码 防止中文乱码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 获取动作
		String op = "";
		// 储存动作
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("queryByPage".equals(op)) {
			// 模糊查询+分页
			doQueryByPage(request, response);
		} else if ("add".equals(op)) {
			// 增加课程
			doAdd(request, response);
		} else if ("del".equals(op)) {
			// 删除课程
			doDel(request, response);
		} else if ("upd".equals(op)) {
			// 修改课程
			doUpd(request, response);
		} else if ("ajaxReqName".equals(op)) {
			// 判断 课程名是否已存在
			doAjaxReqName(request, response);
		} else if ("ajaxReq".equals(op)) {
			// 获得所有课程
			doAjaxReq(request, response);
		}
	}

	/**
	 * 分页+查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 存储课程名关键字
		String keywords = "";
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认为1
		int page = 1;
		// 每页记录数默认为5
		int pageSize = 4;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 调用Service方法
		PageData<Course> pd = cs.getCoursesByPage(page, pageSize, keywords);
		// 传递PageDate对象给JSP
		request.setAttribute("pd", pd);
		request.setAttribute("keywords", keywords);
		// 跳转页面 转发 带request的参数
		request.getRequestDispatcher("Course.jsp").forward(request, response);
	}

	/**
	 * 增加课程
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取文本框的值
		String subJect = request.getParameter("subJect");
		String courseName = request.getParameter("courseName");
		String courseDesc = request.getParameter("courseDesc");
		String coursePic = request.getParameter("coursePic");

		// 调用 service的方法
		Course course1 = cs.getCourseByName(courseName);
		// 传递给JSP的提示信息
		// 默认 课程名存在
		String msg = "课程名已存在，请换一个！";
		int code = 0;
		// 课程名 不存在
		if (course1 == null) {
			// 初始化课程对象
			Course course = new Course(subJect, courseName, courseDesc, coursePic);
			// 调用service的增加方法
			boolean flag = cs.addCourse(course);
			// 默认 增加失败
			msg = "增加失败";
			code = 2;
			if (flag) {
				msg = "增加成功";
				code = 1;
			}
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 将msg转换为json格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		// 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 关闭
		out.close();
	}

	/**
	 * 删除课程
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("到达删除页面");
		// 接收课程号
		String courseNostr = request.getParameter("courseNo");
		// 强制转型
		int courseNo = Integer.parseInt(courseNostr);
		System.out.println(courseNo);
		// 调用service的删除方法
		boolean flag = cs.delCourse(courseNo);
		String msg = "删除失败！";
		int code = 0;
		// 类型名 不存在
		if (flag) {
			msg = "删除成功！";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 7.关闭
		out.close();
	}

	/**
	 * 修改课程
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doUpd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取文本框的值
		String courseNostr = request.getParameter("courseNo");
		int courseNo = Integer.parseInt(courseNostr);
		String subJect = request.getParameter("subJect");
		String courseName = request.getParameter("courseName");
		String courseDesc = request.getParameter("courseDesc");
		String coursePic = request.getParameter("coursePic");
        System.out.println("1111");
		// 初始化课程对象
		Course course = new Course(courseNo, subJect, courseName, courseDesc, coursePic);
		// 调用service的修改方法
		boolean flag = cs.updCourse(course);
		 System.out.println("222"+flag);
		String msg = "修改失败！";
		int code = 0;
		if (flag) {
			msg = "修改成功！";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		 System.out.println("333"+msg);
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		 System.out.println("444"+msg);
		// 7.关闭
		out.close();
	}

	/**
	 * 处理AJAX请求 判断是否存在课程名
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doAjaxReqName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2.获取AJAX请求传递过来的参数
		String courseName = request.getParameter("courseName");
		// 3.调用 service的方法
		Course course = cs.getCourseByName(courseName);
		// 4传递给JSP的提示信息
		// 默认 课程名存在
		String msg = "课程名已存在！";
		int code = 0;
		// 类型名 不存在
		if (course == null) {
			msg = "课程名不存在！";
			code = 1;
		}
		AjaxResponse ar = new AjaxResponse(msg, code);
		// 5将msg1转换为JSON格式的字符串
		Gson gson = new Gson();
		String msgjson = gson.toJson(ar);
		// 6 响应
		PrintWriter out = response.getWriter();
		out.print(msgjson);
		// 7.关闭
		out.close();
	}

	/**
	 * 处理AJAX请求，获得所有课程
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doAjaxReq(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2 调用 service的方法
		List<Course> list = cs.getAllCourses();
		// 3将list转换为JSON格式的字符串
		Gson gson = new Gson();
		String listCourses = gson.toJson(list);
		// 4 响应
		PrintWriter out = response.getWriter();
		out.print(listCourses);
		// 5.关闭
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
